import React from "react";
import moduleCss from "./NewsList.module.css"

class NewsList extends React.Component {

    state = {
        newsList: []
    }
    list = React.createRef<HTMLDivElement>();

    componentDidMount() {
        setInterval(() => {
            let {newsList} = this.state;
            const news = '新闻' + (newsList.length + 1);
            this.setState({newsList: [news, ...newsList]})

        }, 1000)
    }

    getSnapshotBeforeUpdate(prevProps: Readonly<{}>, prevState: Readonly<{}>): any {
        return this.list.current?.scrollHeight;
    }

    componentDidUpdate(prevProps: Readonly<{}>, prevState: Readonly<{}>, snapshot: any) {

        let scrollTop = this.list.current?.scrollTop as number;
        let scrollHeight = this.list.current?.scrollHeight as number;
        scrollTop += scrollHeight - snapshot;
        this.list.current!.scrollTop = scrollTop;
    }

    render() {
        let {newsList} = this.state;
        return (
            <div ref={this.list} className={moduleCss.list}>
                {
                    newsList.map(
                        (value, index) => {
                            return <div key={index} className={moduleCss.news}>{value}</div>
                        }
                    )
                }
            </div>
        )
    }

}

export default NewsList